import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import { isArray } from '@/utils/types'
import microApp from '@/micro-app'

import {
  getAuth,
  removeAuth
} from '@/utils/auth' // 验权

const whiteList = ['login', 'register', 'link'] // 不重定向白名单
const pathWhiteList = ['/404', '/noAuth'] // 不重定向白名单

// 微前端子应用列表
const childrenPath = microApp.map(item => item.activeRule)
// next 到登录
function nextLogin(to, from, next) {
  // 没权限
  if (whiteList.indexOf(to.name) !== -1) {
    next()
  } else {
    if (to.name) {
      next(`/login?redirect=${pathWhiteList.includes(to.path) ? (to.redirectedFrom || '/') : to.path}`) // 否则全部重定向到登录页
    } else {
      next(`/login`) // 第三方登录不能覆盖query参数
    }
  }
}

router.beforeEach(async (to, from, next) => {
  store.commit('CLEAR_CANCEL_TOKEN') // 取消请求
  let redirectedFrom = to.redirectedFrom
  if (from.name === 'login' && to.path === '/404' && redirectedFrom.includes('404')) {
    redirectedFrom = '/' // 可能因重定向导致404 校准一次
  }
  NProgress.start()
  // 允许进入登录页面  1005 需要完善信息 不能清除登录信息
  if (window.accessLogin) {
    next()
    NProgress.done()
    return
  }

  // 请求头包含授权信息 并且 页面必须授权 直接进入
  try {
    await getAuth()
    await store.dispatch('GenerateRoutes')
    if (to.name === 'login') {
      next({
        path: '/oa-front'
      })
    } else {
      if (store.getters.addRouters.length === 0) { // 判断当前用户是否获取权限
        await store.dispatch('QuerySystemModuleList')
        router.addRoutes(store.getters.addRouters)
        if (pathWhiteList.includes(to.path)) {
          if (isArray(store.getters.addRouters) && store.getters.addRouters.length === 0) {
            throw new Error('routeError')
          } else {
            next({
              path: redirectedFrom || '/',
              replace: true
            })
          }
        } else {
          if (childrenPath.some((item) => to.path.includes(item))) {
            next({
              ...to,
              replace: true
            })
          } else {
            next({path: '/404'})
          }
        }
      } else {
        next()
      }
      NProgress.done()
    }
  } catch (error) {
    // 302 登录信息失效 1007 企业用户不存在
    if (error && (error.code === 302 || error.code === 1007)) {
      await removeAuth()
      // 没权限
      nextLogin(to, from, next)
      NProgress.done()
    } else {
      nextLogin(to, from, next)
      console.log('------------------企业微信error------------------')
      console.log(to , from)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})

router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g
  const isChunkLoadFailed = error.message.match(pattern)
  const targetPath = router.history.pending.fullPath
  if (isChunkLoadFailed) {
    router.replace(targetPath)
  }
})
